package internal

import (
	"github.com/golang-module/carbon"
	"github.com/thoas/go-funk"
	"time"
)

func SaveData(from time.Time, to time.Time) {
	queryDate := carbon.Now().StartOfDay()
	beginTime := queryDate.AddHours(from.Hour()).AddMinutes(from.Minute())
	endTime := queryDate.AddHours(to.Hour()).AddMinutes(to.Minute())
	if from.Hour() > to.Hour() {
		queryDate = queryDate.SubDay()
		beginTime = beginTime.SubDay()
	}
	MyLog.Info("计算时间","开始", beginTime, "结束", endTime)
	// 获取当前班次
	workForces := GetWorkForce(queryDate.Time, beginTime.Time, endTime.Time)
	if len(workForces)==0{
		MyLog.Warn("没有发现时间内的排班，取消本次任务")
		return
	}
	// 获取指标和测点
	indexes, tags := GetIndexByCode()
	// 构建查询条件
	query := HistoryQuery{
		BeginTime: beginTime.ToTimestampWithMillisecond(),
		EndTime:   endTime.ToTimestampWithMillisecond(),
		Tags:      tags,
		Type:      "period",
	}
	// 获取测点阶段数据
	result := GeHistoryData(query)
	if len(result)==0{
		MyLog.Warn("没有查询到任何数据，取消本次任务")
		return
	}
	tagValueMap := funk.Map(result, func(x TagValueHistory) (string, interface{}) {
		return x.Code, x.Value
	}).(map[string]interface{})

	buildDataItemList(beginTime,endTime,queryDate,tagValueMap,indexes,workForces)
}
